package com.weiling.common.security;

import com.weiling.common.constant.Constant;
import com.weiling.common.exception.CaptchaException;
import com.weiling.util.RedisUtil;
import com.weiling.util.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Resource
    RedisUtil redisUtil;
    @Resource
    LoginFailureHandler loginFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse, FilterChain filterChain) throws
            ServletException, IOException {
        String url=httpServletRequest.getRequestURI();
        if("/login".equals(url)&&httpServletRequest.getMethod().equals("POST")){
            try{
                validate(httpServletRequest);
            }catch(CaptchaException e){
                // 交给认证失败管理器处理
                loginFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
    /**
     * 校验验证码逻辑
     * @param httpServletRequest
     */
    private void validate(HttpServletRequest httpServletRequest) {
        String code=httpServletRequest.getParameter("code");
        String key=httpServletRequest.getParameter("uuid");
        if(StringUtil.isEmpty(code) || StringUtil.isEmpty(key)){
            throw new CaptchaException("验证码错误！");
        }
        if(!code.equals(redisUtil.hget(Constant.CAPTCHA_KEY,key))){
            throw new CaptchaException("验证码错误！");
        }
    }
}

